package com.scau402.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.scau402.common.constant.TenantConstants;
import com.scau402.common.core.domain.entity.SysUser;
import com.scau402.common.core.domain.model.LoginUser;
import com.scau402.common.utils.DateUtils;
import com.scau402.common.utils.SecurityUtils;
import com.scau402.common.utils.StringUtils;
import com.scau402.common.utils.code.TenantCodeUtils;
import com.scau402.system.domain.WmsJadeType;
import com.scau402.system.domain.vo.SysTenantVO;
import com.scau402.system.service.ISysUserService;
import com.scau402.system.service.IWmsJadeImageService;
import com.scau402.system.service.IWmsJadeTypeService;
import com.scau402.system.service.impl.WmsJadeTypeServiceImpl;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.scau402.common.annotation.Log;
import com.scau402.common.core.controller.BaseController;
import com.scau402.common.core.domain.AjaxResult;
import com.scau402.common.enums.BusinessType;
import com.scau402.system.domain.SysTenant;
import com.scau402.system.service.ISysTenantService;
import com.scau402.common.utils.poi.ExcelUtil;
import com.scau402.common.core.page.TableDataInfo;

/**
 * 租户信息Controller
 * 
 * @author ruoyi
 * @date 2023-06-27
 */
@RestController
@RequestMapping("/system/tenant")
public class SysTenantController extends BaseController
{
    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private IWmsJadeTypeService sysJadeTypeService;

    @Autowired
    private IWmsJadeImageService wmsJadeImageService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询租户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysTenant sysTenant)
    {
        startPage();
        List<SysTenantVO> list = sysTenantService.selectSysTenantList(sysTenant);
        return getDataTable(list);
    }

    /**
     * 导出租户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:export')")
    @Log(title = "租户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysTenant sysTenant)
    {
        List<SysTenantVO> list = sysTenantService.selectSysTenantList(sysTenant);
        ExcelUtil<SysTenantVO> util = new ExcelUtil<SysTenantVO>(SysTenantVO.class);
        util.exportExcel(response, list, "租户信息数据");
    }

    /**
     * 获取租户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:query')")
    @GetMapping(value = "/{tenantId}")
    public AjaxResult getInfo(@PathVariable("tenantId") Long tenantId)
    {
        return success(sysTenantService.selectSysTenantByTenantId(tenantId));
    }

    /**
     * 新增租户信息
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:add')")
    @Log(title = "租户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysTenant sysTenant) {
        // 判断租户编号是否存在
        if (StringUtils.isNotEmpty(sysTenant.getTenantCode()) && !sysTenantService.checkTenantCodeUnique(sysTenant))
        {
            return error("新增租户'" + sysTenant.getTenantCode() + "'失败，租户编号已存在");
        }
        // 判断租户名称是否存在
        if (StringUtils.isNotEmpty(sysTenant.getTenantName()) && !sysTenantService.checkTenantNameUnique(sysTenant))
        {
            return error("新增租户'" + sysTenant.getTenantName() + "'失败，租户名称已存在");
        }
        sysTenant.setCreateBy(getUsername());
        sysTenant.setTenantSource("管理员新建");
        return toAjax(sysTenantService.insertSysTenant(sysTenant));
    }

    /**
     * 修改租户信息
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:edit')")
    @Log(title = "租户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysTenant sysTenant)
    {
        sysTenant.setUpdateBy(getLoginUser().getUsername());
        return toAjax(sysTenantService.updateSysTenant(sysTenant));
    }

    /**
     * 删除租户信息
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:remove')")
    @Log(title = "租户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{tenantIds}")
    public AjaxResult remove(@PathVariable Long[] tenantIds)
    {
        return toAjax(sysTenantService.deleteSysTenantByTenantIds(tenantIds));
    }

    /**
     * 新建租户页面获取租户编码
     * @return 租户编码：根据表sys_tenant字段tenant_code生成自增编码
     * @throws InterruptedException
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:add')")
    @GetMapping("/getTenantCode")
    public String getTenantCode() throws InterruptedException {
        // 返回租户编码
        return sysTenantService.getNewCode();
    }

    /**
     * 获取租户已使用空间
     * @return 租户已使用空间
     * @throws InterruptedException
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:add')")
    @GetMapping("/getTenantSpaceUsed")
    public AjaxResult getTenantSpaceUsed() throws InterruptedException {
        double spaceUsed = wmsJadeImageService.getTenantSpaceUsed(SecurityUtils.getLoginUser().getTenantId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("spaceUsed", spaceUsed);
        return ajax;
    }

    /**
     * 获取跟进人名单 (属于本系统管理员租户 T000001 的用户)
     *
     * @return
     * @throws InterruptedException
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:add')")
    @GetMapping("/getAdminUsers")
    public AjaxResult getAdminUsers() throws InterruptedException {
        List<SysUser> salesPersonList = sysUserService.selectSalesPersonUsers();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("salesPersonList", salesPersonList);
        return ajax;
    }

    /**
     * 获取待审核租户列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:list')")
    @GetMapping("/reviewList")
    public TableDataInfo getReviewList(SysTenant sysTenant)
    {
        startPage();
        List<SysTenant> list = sysTenantService.selectSysTenantReviewList(sysTenant);
        return getDataTable(list);
    }

    /**
     * 审核租户注册
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:tenant:add')")
    @PostMapping("/reviewTenant")
    public AjaxResult reviewTenant(@RequestBody String params)
    {
        // 转换为 list 格式
        JSONObject paramsJson =  JSON.parseObject(params);
        Long id = paramsJson.getLong("tenantId");
        String review = paramsJson.getString("review");

        SysTenant tenant = sysTenantService.selectSysTenantByTenantId(id);

        // 提交审核检查
        if(!(review.equals(TenantConstants.UNREVIEW) || review.equals(TenantConstants.REVIEW_PASS) || review.equals(TenantConstants.REVIEW_REJECT))) {
            return error("错误的审核提交");
        }

        // 已经通过审核不能再次审核
        if(!tenant.getReview().equals(TenantConstants.UNREVIEW)) {
            return error(tenant.getTenantName()+"已经审核完毕，不能更改为未审核");
        }

        // 提交相同审核结果
        if(tenant.getReview().equals(review)) {
            return error("审核状态已为"+review);
        }

        if(sysTenantService.reviewTenant(tenant, review).equals(TenantConstants.REVIEW_PASS)) {
            return success("审核通过");
        } else if (sysTenantService.reviewTenant(tenant, review).equals(TenantConstants.REVIEW_REJECT)){
            return success("审核不通过");
        } else {
            return success();
        }
    }

}
